package com.coffee.core.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * math utils
 *
 * @author xulg 2019年6月01日
 */
@SuppressWarnings("unused")
public class WebUtil {
    private static Logger logger = LoggerFactory.getLogger(WebUtil.class);

    /**
     * 获取cookie值
     *
     * @param request the request
     * @param key     the cookie key
     * @return the cookie value
     */
    public static String getCookieValue(HttpServletRequest request, String key) {
        if (request == null || StringUtils.isBlank(key)) {
            return null;
        }
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length <= 0) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (key.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }
        return null;
    }

    /**
     * 获取cookie值然后删除cookie
     *
     * @param request  the request
     * @param response the response
     * @param key      the cookie key
     * @return the cookie value(or null)
     */
    public static String getCookieValueThenDelete(HttpServletRequest request, HttpServletResponse response, String key) {
        if (request == null || StringUtils.isBlank(key)) {
            return null;
        }
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length <= 0) {
            return null;
        }
        String cookieValue = null;
        boolean shouldDelete = false;
        for (Cookie cookie : cookies) {
            if (key.equals(cookie.getName())) {
                cookieValue = cookie.getValue();
                shouldDelete = true;
            }
        }
        if (shouldDelete) {
            deleteCookie(response, key);
        }
        return cookieValue;
    }

    /**
     * 写入cookie
     *
     * @param response the response
     * @param key      the cookie key
     * @param value    the cookie value
     * @param expire   过期时间(秒)
     */
    public static void addCookie(HttpServletResponse response, String key, String value, int expire) {
        Cookie cookie = new Cookie(key, value);
        cookie.setPath("/");
        cookie.setMaxAge(expire);
        response.addCookie(cookie);
    }

    /**
     * 写入cookie
     *
     * @param response the response
     * @param key      the cookie key
     * @param value    the cookie value
     * @param expire   过期时间(秒)
     * @param httpOnly is http only
     */
    public static void addCookie(HttpServletResponse response, String key, String value, int expire, boolean httpOnly) {
        Cookie cookie = new Cookie(key, value);
        cookie.setPath("/");
        cookie.setMaxAge(expire);
        cookie.setHttpOnly(httpOnly);
        response.addCookie(cookie);
    }

    /**
     * 写入7天有效的cookie
     *
     * @param response the response
     * @param key      the cookie key
     * @param value    the cookie value
     */
    public static void addCookie(HttpServletResponse response, String key, String value) {
        Cookie cookie = new Cookie(key, value);
        cookie.setPath("/");
        cookie.setMaxAge(24 * 60 * 60 * 7);
        response.addCookie(cookie);
    }

    /**
     * 写入7天有效的cookie
     *
     * @param response the response
     * @param key      the cookie key
     * @param value    the cookie value
     */
    public static void addCookie(HttpServletResponse response, String key, String value, String domain) {
        Cookie cookie = new Cookie(key, value);
        cookie.setPath("/");
        cookie.setDomain(domain);
        cookie.setMaxAge(24 * 60 * 60 * 7);
        response.addCookie(cookie);
    }

    /**
     * 删除cookie
     *
     * @param response the response
     * @param key      the cookie key
     */
    public static void deleteCookie(HttpServletResponse response, String key) {
        Cookie cookie = new Cookie(key, null);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

    public static String getParameter(HttpServletRequest request, String name, String defaultValue) {
        return StringUtils.defaultIfBlank(request.getParameter(name), defaultValue);
    }

    public static String getParameter(HttpServletRequest request, String name) {
        return request.getParameter(name);
    }

    /**
     * is ajax request
     *
     * @param request       the request
     * @param response      the response
     * @param handlerMethod the handler method
     * @return is ajax request
     */
    @SuppressWarnings("Duplicates")
    public static boolean isAjaxRequest(HttpServletRequest request,
                                        HttpServletResponse response,
                                        HandlerMethod handlerMethod) {
        String accept = request.getHeader("accept");
        String xRequestedWith = request.getHeader("X-Requested-With");
        Method method = handlerMethod.getMethod();
        Class<?> clazz = method.getDeclaringClass();
        return accept.contains("application/json")
                || method.isAnnotationPresent(ResponseBody.class)
                || clazz.isAnnotationPresent(ResponseBody.class)
                || clazz.isAnnotationPresent(RestController.class)
                || response.getContentType().contains("application/json")
                || StringUtils.defaultIfBlank(response.getContentType(), "")
                .contains("application/json")
                || (xRequestedWith != null && xRequestedWith.contains("XMLHttpRequest"));
    }
    
	public static String getUserAgent(HttpServletRequest request) {
		return request.getHeader("user-agent");
	}
}
